<?php

namespace Common\Model;

use Think\Model;

class ArticleTagModel extends Model
{
    /**
     * 通过文章ID获取TAG
     *
     * @param string $aid
     * @return array
     */
    public function get_tag_qid($aid = '')
    {
        $map['aid'] = intval($aid);
        $tag        = $this->where($map)->select();
        foreach ($tag as $v) {
            $v['tagurl'] = RU('tag/view', array('t' => $v['tagid'], 'type' => 2));
            $tags[]      = $v;
        }
        return $tags;
    }

    /**
     * 通过TAGID获取最新
     *
     * @param string $tagid
     * @param string $limit
     * @return mixed
     */
    public function get_tag_tagid($tagid = '', $limit = '')
    {
        $map['tagid'] = intval($tagid);
        $tag          = $this->where($map)->order('id DESC')->limit($limit)->select();
        return $tag;
    }

    /**
     * 添加文章标签
     * @param array $tagNames
     * @param int   $aid
     * @param int   $uid
     */
    public function batch_add(array $tagNames, $aid, $uid)
    {
        if (!empty($tagNames)) { //插入标签
            if (is_array($tagNames)) {
                $map['aid'] = $aid;
                $map['uid'] = $uid;
                foreach ($tagNames as $tagName) {
                    $map['tagid'] = D('Tag')->get_tagid($tagName);  // 不存在则先注册
                    $map['tag']   = $tagName;
                    M('ArticleTag')->add($map);
                    $this->on_article_tag_add($map['tagid'], $aid, $uid);
                }
            }
        }
    }

    /**
     * 添加文章标签事件行为
     * @param int $tagid TagID
     * @param int $aid   文章ID
     * @param int $uid   添加用户ID
     */
    protected function on_article_tag_add($tagid, $aid, $uid)
    {
        D('Tag')->set_tag_count($tagid, 'count_article');  // 更新Tag下的文章总数
    }

    /**
     * @param array|string $ids
     */
    public function atag_del($ids)
    {
        $list = M('ArticleTag')->select($ids);
        if ($list) {
            M('ArticleTag')->delete($ids);
            $this->on_atag_del($list);
        }
    }

    /**
     * @param array $list
     */
    protected function on_atag_del($list)
    {
        $tagIds = array_column($list, 'tagid');

        D('Tag')->set_tag_count($tagIds, 'count_article');  // 更新标签统计
    }

}